{% set isNarrow = true %}


{% extends "./layout/layout.html" %}

{% block content %}
<div class="container">
  {% if isLogin %}
  <p>欢迎{{userName}},您已登录，请返回<a href="/">首页</a></p>
  {% else %}
  <h1>登录</h1>
  <hr>
  <form>
    <div class="form-group">
      <label for="username-input">用户名</label>
      <input type="text" class="form-control" id="username-input" placeholder="请输入用户名">
    </div>
    <div class="form-group">
      <label for="password-input">密码</label>
      <input type="password" class="form-control" id="password-input" placeholder="请输入密码">
    </div>
    <button type="submit" class="btn btn-primary do-login">登录</button>
    <a href="/register">注册账号>></a>
  </form>
  {% endif %}
</div>
{% endblock %}

{% block js %}
<script>
  $(".do-login").click(function (e) {
    // 阻止默认行为
    e.preventDefault()
    // 获取用户名和密码
    const userName = $("#username-input").val();
    const password = $("#password-input").val();
    ajax.post("/api/user/login", { userName, password }, function (err, data) {
      if (err) {
        alert(err);
        return;
      }
      alert("登录成功")
      let search = location.search;
      // 转换成正确的地址
      let redirectUrl = decodeURIComponent(search.split("=")[1]);
      // 重定向
      if (redirectUrl === "undefined") {
        location.href = "/";
      } else {
        location.href = redirectUrl;
      }
    })
    // 发送给后台
    /* $.ajax({
      type: "post",
      url: "/api/user/login",
      data: { userName, password },
      success(result) {
        console.log(location.search)
        if (result.errno === 0) {
          alert("登录成功");
          // 获取查询的内容
          let search = location.search;
          // 转换成正确的地址
          let redirectUrl = decodeURIComponent(search.split("=")[1]);

          // 重定向
          if (redirectUrl === "undefined") {
            location.href = "/";
          } else {
            location.href = redirectUrl;
          }
        } else {
          alert(result.message);
        }
      },
      error(err) {
        console.log(err)
      }
    }) */
  })

</script>

{% endblock %}